<!-- 添加地址组件 -->
<template>
  <div class v-loading="loading">
    <el-form
      ref="addressFormRef"
      :model="addressform"
      label-width="200px"
      :rules="addressRules"
      class="address-form"
    >
    <el-form-item label="地址链接" prop="link">
        <el-input v-model="addressform.link" placeholder="输入地址链接自动识别" @blur="getLink"></el-input>
      </el-form-item>
      <el-form-item label="货主公司" prop="owner_id">
        <el-select
          filterable
          v-model="addressform.owner_id"
          placeholder="请选择货主公司"
        >
          <el-option
            v-for="(item, index) in companyList"
            :key="index"
            :label="item.company_name"
            :value="item.owner_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在地区" prop="areaArr">
        <el-cascader v-model="addressform.areaArr" :options="regionData" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="详细地址" prop="detail">
        <el-input v-model="addressform.detail"></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="name">
        <el-input v-model="addressform.name"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="addressform.phone"></el-input>
      </el-form-item>
      <el-form-item label>
        <el-button type="primary" @click="onSubmitAddress('addressFormRef')">添加新地址</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getAllCompany, addAddress } from "@/api/release";
import { regionData } from "element-china-area-data";
import { getCodeToText } from "@/utils/tool.js";
import {reverseGeocoding} from "@/api/public";
export default {
  props: {
    companyList: {
      default: [],
      type: Array
    }
  },
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var validatePhone = (rule, value, callback) => {
      if (
        !/^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/.test(
          value
        )
      ) {
        callback(new Error("请输入正确的手机号格式"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      regionData,
      addressRules: {
        owner_id: [
          { required: true, message: "请选择货主公司", trigger: "change" }
        ],
        areaArr: [
          { required: true, message: "请选择选择收货地区", trigger: "change" }
        ],
        detail: [
          { required: true, message: "请填写详细地址", trigger: "change" }
        ],
        name: [{ required: true, message: "请填写联系人", trigger: "change" }],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: ["blur", "change"]
          }
        ]
      },
      addressform: {
        areaArr: "", //选择的省市区数组
        phone: "",
        name: "",
        detail: "",
        city_code: "",
        province: "", //省
        city: "", //城市
        area: "", //区
        owner_id:'',
        link:""
      },
      loading: false
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //根据地址链接识别地址地址信息
   async getLink(el){
      let vaule = el.target.value;
      // let url = decodeURIComponent(`https://map.qq.com/?addr=%E4%BF%A1%E9%83%BD%E5%8C%BAS322&isopeninfowin=1&markertype=1&name=%E4%BF%A1%E9%83%BD%E5%8C%BA%E6%99%B6%E6%9D%B0%E4%B8%AD%E7%A9%BA%E7%8E%BB%E7%92%83%E9%97%A8%E7%AA%97%E5%8E%82%28S322%E5%8D%97%29&pointx=114.327&pointy=37.0764&ref=WeChat&type=marker`);
      let url = decodeURIComponent(vaule);
      let addressInfo = {};
      if(url.split("?")[1]){
        let arr = url.split("?")[1].split("&");
        arr.forEach(item=>{
          let key = item.split('=')[0];
          let value = item.split('=')[1];
          addressInfo[key] = value;
        });
        console.log('addressInfo',addressInfo);

        let result = await reverseGeocoding({
          location: [addressInfo.pointy,addressInfo.pointx].join(","),
        });
        if(result.code == 200){
          let city_code = result.data.adcode + ''; //省市区code
          let areaArr = [city_code.slice(0,2),city_code.slice(0,4),city_code]; //选择的省市区数组
          if (city_code) {
            this.addressform.areaArr = areaArr;
            this.addressform.city_code = areaArr[2];
            let codeArr = getCodeToText(areaArr);
            this.addressform.province = codeArr[0];
            this.addressform.city = codeArr[1];
            this.addressform.area = codeArr[2];
            this.addressform.detail = addressInfo.name;
          }
      
        }else{
          this.$message({
          type: "error",
          message: "地址链接识别失败"
        });
        }
        console.log('失焦了',result);
      }else{
        this.$message({
          type: "error",
          message: "请输入有效的地址链接"
        });
      }
    },
    //添加新地址
    async onSubmitAddress(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          console.log(this.addressform);
          this.loading = true;
          if (this.addressform.areaArr) {
            this.addressform.city_code = this.addressform.areaArr[2];
          }
          let codeArr = getCodeToText(this.addressform.areaArr);
          this.addressform.province = codeArr[0];
          this.addressform.city = codeArr[1];
          this.addressform.area = codeArr[2];
          let res = await addAddress({
            province: this.addressform.province,
            city: this.addressform.city,
            area: this.addressform.area,
            name: this.addressform.name,
            phone: this.addressform.phone,
            detail: this.addressform.detail,
            city_code: this.addressform.city_code,
            owner_id: this.addressform.owner_id
          });
          this.loading = false;
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: true ? "添加地址成功!" : "编辑地址成功!"
            });
            this.$emit("addSuccess", false);
          } else {
            this.$message({
              type: "error",
              message: res.info
            });
            this.$emit("addSuccess", false);
          }
        } else {
          return false;
        }
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // console.log("this.companyList", this.companyList);
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>